const { default: DPagination } = require("../../../utils/DPagination");
const { getProjectNameLang } = require("../common");
var location = require("../../../mybehaviors/location/location");


// packageH/project_verification/MyProject/MyProject.js
const App = getApp();
const GetUnUseProjectUrl = App.getNetAddresss("plugin.store-projects.frontend.project-order.get-un-finish-list");
const GetUsedProjectUrl = App.getNetAddresss("plugin.store-projects.frontend.project-order.get-finish-list");
const ProjectsPagination = new DPagination("projects");
let Location = null;
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    currentShowPageTab: "0",
    projects: {},
    projectCount: 0,
    projectNameLang: getProjectNameLang(),
    showGivePop: false,
    giveInfo: {},
    giveUserId:'',
    giveNum:'',
    nickname:"",
    errorFlag:false,
    errorMsg:'',
    timeStyle:"0",
    addressValue:"",
    Location: {},
    imgPath: App.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if(options.Location){
      let Location =JSON.parse(options.Location);
      this.setData({Location});
    }
    this._getLocation((res,point) => {
      Location = {
        point: point
      };
      this.getProjects();
    });

    ProjectsPagination.bind(this);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    ProjectsPagination.clean();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    ProjectsPagination.clean();
    this.getProjects();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getProjects();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  switchPageTabs({ detail: { name } }) {
    this.setData({
      currentShowPageTab: name,
    });
    ProjectsPagination.clean();
    this.getProjects();
  },
  timeSort({currentTarget:{dataset:{val}}}){
    let {timeStyle} = this.data;
    if(val===true){
      timeStyle = timeStyle ==2?3:2;
    }else{
      timeStyle = timeStyle==0?1:0;
    }
    this.setData({timeStyle});
    ProjectsPagination.clean();
    this.getProjects();
  },
  getProjects() {
    if (ProjectsPagination.loading || ProjectsPagination.finished) {
      return;
    }
    ProjectsPagination.loading = true;
    let url = GetUnUseProjectUrl;
    let point = App.qqMapTransBMap(parseFloat(Location.point.lng), parseFloat(Location.point.lat));
    let data = {
      page: ProjectsPagination.loadPage,
      lat: point.lat,
      lng: point.lng,
    };
    let loct = this.data.Location;
    if(Object.keys(loct).length>0){
      data.lat = loct.latitude;
      data.lng = loct.longitude;
      this.setData({addressValue:loct.message});
    }else{
      this.setData({addressValue:Location.address});
    }
    if (this.data.currentShowPageTab === "1") {
      url = GetUsedProjectUrl;
    }else{
      data.orderby = this.data.timeStyle;
    }
    wx.showLoading();
    App._getNetWork({
      url,
      data,
      success: ({ data: { data: response, result, msg } }) => {
        ProjectsPagination.loading = false;
        wx.stopPullDownRefresh();
        wx.hideLoading();
        if (result == 0) {
          wx.showToast({
            title: msg,
            icon: "none",
          });
          return;
        }
        if (response.current_page == response.last_page || response.data.length < response.per_page) {
          ProjectsPagination.finished = true;
        }
        ProjectsPagination.push(response.data);
        this.setData({
          projectCount: ProjectsPagination.length,
        });
      },
    });
  },

  tapBtnGive (event) {
    let obj = event.currentTarget.dataset.item;
    this.setData({
      showGivePop: true,
      giveInfo: obj
    });
  },
  tolink(event){
    console.log(event)
    let urls = event.currentTarget.dataset.url;
    wx.navigateTo({
      url: urls,
    })
  },
  // 关闭弹框
  closeGivePop () {
    this.setData({
      showGivePop: false,
    });
  },
  // 确定赠送
  giveProject () {
    if (!this.data.giveUserId) {
      this.setData({
        errorFlag:true,
        errorMsg:'请输入用户'
      });
      return;
    }
    if(this.data.errorFlag){
      this.setData({errorMsg:'查无此用户',errorFlag:true});
      return;
    }

    if (!this.data.giveNum) {
      this.setData({
        errorNum:'转增次数不能为空'
      });
      return;
    }
    if (this.data.giveInfo.rest_count < this.data.giveNum) {
      this.setData({
        errorNum:'输入转赠次数大于拥有的次数'
      });
      return;
    }

    let urlStr = App.getNetAddresss("plugin.store-projects.frontend.project-order.transfer");
    App._getNetWork({
      url:urlStr,
      data: {id: this.data.giveInfo.id,
        transfer_uid: this.data.giveUserId,
        transfer_count: this.data.giveNum},
      success: (resdata) => {
        let res = resdata.data;
        console.log(res.msg);
        App.tips(res.msg);
        if(res.result == 1){
          this.closeGivePop();
          ProjectsPagination.clean();
          this.getProjects();
        }

      }
    });
  },

  throttleFn(evt){
    let uid = evt.detail;
    this.data.giveUserId = uid;
    this.data.errorFlag = true;
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    this.timeoutId = setTimeout(()=> {
      this.searchUser(uid);
    }, 1000);
  },
  searchUser(uid){
    let urlStr = App.getNetAddresss("member.member.memberInfo");
    console.log(urlStr);
    App._getNetWork({
      url:urlStr,
      data: {uid},
      success: (resdata) => {
        let res = resdata.data;
        if(res.result == 1 && res.data !=null){
          this.setData({
            nickname:res.data.nickname,errorFlag:false,giveUserId:uid
          });
        }else {
          this.setData({errorFlag:true,errorMsg:'查无此用户'});
        }

      },
      fail:()=>{
        this.setData({giveUserId:'',errorFlag:true,errorMsg:'查无此用户'});
      }
    });
  },
  changeNumInput (event) {
    console.log(event);
    let num = this.data.giveNum;
    let errorNum = '';
    if (num<=0) {
      errorNum = "转增次数不能为空";
    }else if (this.data.giveInfo.rest_count < num) {
      errorNum = "输入转赠次数大于拥有的次数";
    }
    this.setData({errorNum});
  },




});
